<?php

namespace models;

//如
// 1. http://www.dianping.com/shop/59167499
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use util\CommonUtil;
use util\Constant;

class NuoMiSpider extends BaseSpider {

    public $cookieStr;   // cookie

    // 初始化webUrl、apiUrl
    function __construct($url, $ua){
        $this->ua = $ua;
        $this->webUrl = $url;
        $file_contents = '';
        try {

            // start Firefox with 5 second timeout
            $host = 'http://localhost:4444/wd/hub'; // this is the default
            $capabilities = DesiredCapabilities::chrome();
            $options = new ChromeOptions();
            $options->addArguments(["user-agent={$this->ua}"]);
            $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
            $driver = RemoteWebDriver::create($host, $capabilities, Constant::$CONNECTION_TIMEOUT_IN_MS);
            $driver->manage()->timeouts()->implicitlyWait(Constant::$IMPLICITLY_WAIT);
            $driver->manage()->window()->maximize();    //将浏览器最大化
            $driver->get($url);   //先访问网页，获取到内容
            $cookies = $driver->manage()->getCookies();
            $cookieStr = '';
            foreach ($cookies as $cookie) {
                $cookieStr .= "{$cookie['name']}={$cookie['value']};";
            }
            $this->cookieStr = $cookieStr;
            $file_contents = CommonUtil::getPageSource($driver);

            CommonUtil::shutdownChrome($driver);
        }catch (\Exception $e) {

            if (!empty($driver)){
                $driver->manage()->deleteAllCookies();  //清除COOKIES，主要是清除百度的“访客标识码”
            }
            CommonUtil::shutdownChrome($driver);

            CommonUtil::logException($e);   //记录异常信息
            CommonUtil::echoStr($msg = "\n发生异常，过滤本次任务~\n");
        }

        $html = str_get_html($file_contents);
        $mon = $html->find('div[class=p-bread-crumb]',0)->attr['mon'];

        $id = explode('=',$mon)[1];
        if ($id != 0) {
            $this->apiUrl = "https://www.nuomi.com/pcindex/main/comment?label=&label_type=0&page=1&sort=0&level=0&t=1507693625169&dealId={$id}&_=1507693578303";
        }


    }

    // 获取评论列表，仅处理10条
    public function getComments(){

        if (empty($this->apiUrl)) return [];

        $ch = curl_init();
        $timeout = 30;
        curl_setopt ($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 检查证书中是否设置域名*/
        curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
        curl_setopt($ch,CURLOPT_COOKIE,$this->cookieStr);
        $file_contents = curl_exec($ch);
        curl_close($ch);

        $json = json_decode($file_contents);
        $arr = array();
        foreach ($json->data->list as $li){
            $avatar = $li->figure;//用户头像地址
            $name = $li->nickname;//用户昵称
            $time = $li->update_time;//评论时间
            $content = $li->content;//用户评论
            $picUrlStr = '';
            foreach ($li->pic_url as $pic){
                if (!empty($picUrlStr)) $picUrlStr .= ',';
                $picUrlStr .= "http:".$pic;
            }
            $obj = array();
            $obj['head'] = CommonUtil::replace2https($avatar);   //头像
            $obj['nickname'] = trim($name);  //昵称
            $obj['content'] = trim($content);    //评论内容
            $obj['comment_time'] = trim($time);   //评论时间
            $obj['pic_urls'] = $picUrlStr;   //评论图片
            $arr[] = $obj;

        }

        return $arr;

    }

}